package com.djk.controller;

import com.djk.pojo.Result;
import com.djk.pojo.ResultCodeEnum;
import com.djk.pojo.SysUser;
import com.djk.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    /**
     * 处理登录请求
     * 请求参数：json
     *
     * @return
     */
    @RequestMapping("/login")
    public Result login(@RequestBody SysUser loginUser) {
        SysUser sysUser = sysUserService.findUser(loginUser.getUsername());
        String loginPwd = loginUser.getUserPwd();
        Result result = null;
        //校验用户名和密码
        if (sysUser != null) {
            String userPwd = sysUser.getUserPwd();
            sysUser.setUserPwd("");
            //密码正确
            if (userPwd.equals(loginPwd)) {
                result = Result.ok(sysUser);
            } else {
                //密码错误
                result = Result.build(sysUser, ResultCodeEnum.PASSWORD_ERROR);
            }
        } else {
            //用户不存在
            result = Result.build(sysUser, ResultCodeEnum.USERNAME_ERROR);
        }
        return result;
    }

    /**
     * 检验用户名是否被占用
     * 请求参数：查询字符串
     *
     * @param username
     * @return
     */
    @RequestMapping("/checkUsernameUsed")
    public Result checkUsernameUsed(String username) {
        SysUser user = sysUserService.findUser(username);
        Result result = null;
        if (user != null) {
            result = Result.build(null, ResultCodeEnum.USERNAME_USED);
        } else {
            result = Result.ok(null);
        }
        return result;
    }

    /**
     * 处理注册请求
     * 请求参数：json
     *
     * @return
     */
    @RequestMapping("regist")
    public Result regist(@RequestBody SysUser sysUser) {
        String username = sysUser.getUsername();
        String pwd = sysUser.getUserPwd();
        Result result = null;
        //先确认该用户名是否被抢先注册
        SysUser user = sysUserService.findUser(username);
        if (user != null) {
            //存在，注册失败
            result = Result.build(null, ResultCodeEnum.USERNAME_USED);
        } else {
            //成功，就添加该用户
            sysUserService.addUser(new SysUser(null, username, pwd));
            result = Result.ok(null);
        }
        return result;
    }
}
